package com.guandi.geekbrowser.controller;

import com.alibaba.fastjson.JSONObject;
import com.guandi.geekbrowser.Utils.DESHelper;
import com.guandi.geekbrowser.Utils.EasyUtil;
import com.guandi.geekbrowser.primary.entity.*;
import com.guandi.geekbrowser.primary.service.DetailsService;
import com.guandi.geekbrowser.primary.service.IpoolService;
import com.guandi.geekbrowser.primary.service.TaskItemService;
import com.guandi.geekbrowser.primary.service.TaskManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class APIController {

    @Autowired
    private DetailsService detailsService;

    @Autowired
    private IpoolService ipoolService;

    @Autowired
    private TaskItemService taskItemService;

    @Autowired
    private TaskManageService taskManageService;

    private DESHelper desHelper = new DESHelper("zDsGrVKQ");

    public String convertCountry(String country) {
        String tempCountry = null;
        if (EasyUtil.isEmpty(country)) {
            country = "美国";
        }
        switch (country) {
            case "美国":
                tempCountry = Country.US.name();
                break;
            case "英国":
                tempCountry = Country.UK.name();
                break;
            case "法国":
                tempCountry = Country.FR.name();
                break;
            case "德国":
                tempCountry = Country.DE.name();
                break;
            case "日本":
                tempCountry = Country.JP.name();
                break;
            case "意大利":
                tempCountry = Country.IT.name();
                break;
            case "澳大利亚":
                tempCountry = Country.AU.name();
                break;
            case "西班牙":
                tempCountry = Country.ES.name();
                break;
            default:
                tempCountry = "";
        }
        return tempCountry;
    }

    @RequestMapping(value = "/getDetail", method = RequestMethod.POST)
    @ResponseBody
    public String getDetail(@RequestBody JSONObject jsonObject) {
        String userId = (String) jsonObject.get("userId");
        String country = (String) jsonObject.get("country");
        userId = desHelper.decrypt(userId);
        Integer detailId = (Integer) jsonObject.get("detailId");
        Long detailId1 = Long.valueOf(detailId.longValue());
        country = convertCountry(country);
        Details detail = detailsService.findByIdAndUserIdAndCountry(detailId1, userId, country);
        String str = JSONObject.toJSONString(detail);
        return str;
    }

    @RequestMapping(value = "/getIp", method = RequestMethod.POST)
    @ResponseBody
    public String getIp(@RequestBody JSONObject jsonObject) {
        String userId = (String) jsonObject.get("userId");
        String country = (String) jsonObject.get("country");
        userId = desHelper.decrypt(userId);
        country = convertCountry(country);
        Page<Ipool> ipools = ipoolService.findByUserIdUseStatusTypeCountryBindOrderByPortASCPage(userId, 0, 0, 0, country);
        if (!ipools.isEmpty()) {
            Ipool ipool = ipools.getContent().get(0);
            ipool.setUsestatus(1);
            ipoolService.saveIpool(ipool);
            return JSONObject.toJSONString(ipool);
        } else {
            return "没有对应数据啦!!";
        }
    }

    @RequestMapping(value = "/getLastIp", method = RequestMethod.POST)
    @ResponseBody
    public String getLastIp(@RequestBody JSONObject jsonObject) {
        String userId = (String) jsonObject.get("userId");
        String country = (String) jsonObject.get("country");
        country = convertCountry(country);
        userId = desHelper.decrypt(userId);
        List<Ipool> content = ipoolService.findByUserIdUseStatusTypeCountryBindOrderByPortASCPage(userId, 0, 0, 0, country).getContent();
        if (!content.isEmpty()) {
            Ipool ipool = content.get(0);
            String address = ipool.getAddress() + ":" + ipool.getPort();
            ipool.setAddress(address);
            return JSONObject.toJSONString(ipool);
        } else {
            return "failed";
        }
    }

    @RequestMapping(value = "/updateIp", method = RequestMethod.POST)
    @ResponseBody
    public boolean updateIp(@RequestBody JSONObject jsonObject) {
        String address = jsonObject.getString("address");
        String port = jsonObject.getString("port");
        String uuid = jsonObject.getString("uuid");
        uuid = desHelper.decrypt(uuid);
        Ipool ipoolTemp = ipoolService.findByAddressAndPortAndUserId(address, port, uuid);
        if (ipoolTemp != null) {
            ipoolService.updateUsestatus(ipoolTemp.getId(), 0);
            return true;
        }
        return false;
    }

    /**
     * 获取注册账号,如账号存在则改变为注册过状态
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/getRegisterDetail", method = RequestMethod.POST)
    @ResponseBody
    public String getRegisterDetail(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String tabName = jsonObject.getString("tabName");
        String country = jsonObject.getString("country");
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(tabName)) {
            userId = desHelper.decrypt(userId);
            country = convertCountry(country);
            List<Details> details = detailsService.findByTabNameAndUserIdAndCountryQuery(tabName, userId, country);
            if (details != null && details.size() > 0) {
                return JSONObject.toJSONString(details.get(0));
            } else {
                return "账号不存在!";
            }
        } else {
            return "参数不对!";
        }
    }


    /**
     * 用户注册账号判断IP是否重复
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/registerDetail", method = RequestMethod.POST)
    @ResponseBody
    public String registerDetail(@RequestBody JSONObject jsonObject) throws Exception {
        String userId = (String) jsonObject.get("userId");
        String detailId = (String) jsonObject.get("detailId");
        String luminati = (String) jsonObject.get("luminati");
        String country = (String) jsonObject.get("country");
        Message message = new Message();
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(country)) {
            country = convertCountry(country);
            userId = desHelper.decrypt(userId);
            Ipool ipool = ipoolService.findByUserIdAndTypeQuery(userId, 0);
            if (ipool != null) {
                if (!EasyUtil.isEmpty(luminati)) {
                    String[] split = luminati.split(":");
                    String ip = split[0];
                    String port = split[1];
                    List<Details> detailTemp = detailsService.findByRegIp(ip);
                    //ip没有被使用{
                    Details detail = detailsService.findByIdAndUserId(Long.parseLong(detailId), userId);
                    if (detailTemp.isEmpty()) {
                        if (detail != null) {
                            detail.setRegisterDate(new Date());
                            detail.setRegIp(ip);
                            detail.setRegister(true);
                            detailsService.saveDetails(detail);
                            message.setMessage("开始注册!");
                            message.setSuccess(true);
                        } else {
                            message.setMessage("详细信息不存在!");
                            message.setSuccess(false);
                        }
                    } else {
                        //刷新IP
                        if (detail != null) {
                            boolean refreshIp = EasyUtil.refreshIp(ipool.getAddress(), port);
                            if (refreshIp) {
                                detail.setRegisterDate(new Date());
                                detail.setRegIp(ip);
                                detail.setRegister(true);
                                detailsService.saveDetails(detail);
                                message.setSuccess(true);
                                message.setMessage("ip已刷新!");
                            } else {
                                message.setSuccess(false);
                                message.setMessage("ip刷新失败!");
                            }
                        } else {
                            message.setSuccess(false);
                            message.setMessage("详细信息不存在!");
                        }
                    }
                } else {
                    Page<Ipool> ipoolPage = ipoolService.findByUserIdUseStatusTypeCountryBindOrderByPortASCPage(userId, 0, 0, 0, country);
                    if (!ipoolPage.isEmpty()) {
                        Ipool ipoolTemp = ipoolPage.getContent().get(0);
                        String port = ipoolTemp.getPort();
                        String ip = EasyUtil.getRegisterIp(ipoolTemp.getAddress(), port);
                        if (!EasyUtil.isEmpty(ip)) {
                            JSONObject temp = JSONObject.parseObject(ip);
                            String ipTemp = temp.getString("ip");
                            boolean isIp = EasyUtil.checkIp(ipTemp);
                            if (isIp) {
                                List<Details> details = detailsService.findByRegIpAndCountry(ipTemp, country);
                                //ip没有被使用{
                                Details detail = detailsService.findByIdAndUserIdAndCountry(Long.parseLong(detailId), userId, country);
                                if (details.isEmpty()) {
                                    if (detail != null) {
                                        detail.setRegisterDate(new Date());
                                        detail.setRegister(true);
                                        detail.setRegIp(ipTemp);
                                        detail.setCountry(country);
                                        detailsService.saveDetails(detail);
                                        message.setSuccess(true);
                                        message.setMessage("开始注册!");
                                    } else {
                                        message.setSuccess(false);
                                        message.setMessage("详细信息不存在!");
                                    }
                                } else {
                                    //刷新IP
                                    boolean refreshIp = EasyUtil.refreshIp(ipool.getAddress(),port);
                                    if (refreshIp) {
                                        ip = EasyUtil.getRegisterIp(ipoolTemp.getAddress(), port);
                                        temp = JSONObject.parseObject(ip);
                                        ipTemp = temp.getString("ip");
                                        if (detail != null) {
                                            detail.setRegisterDate(new Date());
                                            detail.setRegIp(ipTemp);
                                            detail.setRegister(true);
                                            detail.setCountry(country);
                                            detailsService.saveDetails(detail);
                                            message.setMessage("ip已刷新!");
                                            message.setSuccess(true);
                                        } else {
                                            message.setMessage("详细信息不存在!");
                                            message.setSuccess(false);
                                        }
                                    } else {
                                        message.setSuccess(false);
                                        message.setMessage("ip刷新失败!");
                                    }
                                }
                            } else {
                                message.setSuccess(false);
                                message.setMessage("IP端口不合法!");
                            }
                        } else {
                            message.setSuccess(false);
                            message.setMessage("注册IP为空!");
                        }
                    } else {
                        message.setSuccess(false);
                        message.setMessage("没有可以使用的IP!");
                    }

                }
            } else {
                message.setSuccess(false);
                message.setMessage("IP数据为空!");
            }
        }
        return JSONObject.toJSONString(message);
    }

    /**
     * 更新账号密码
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public String updatePassword(@RequestBody JSONObject jsonObject) {
        String detailId = jsonObject.getString("detailId");
        String password = jsonObject.getString("password");
        String userId = jsonObject.getString("userId");
        userId = desHelper.decrypt(userId);
        Integer integer = detailsService.updatePassword(Long.parseLong(detailId), password, userId);
        return integer.toString();
    }

    /**
     * 更新账号pcCookie
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/updatePcCookie", method = RequestMethod.POST)
    @ResponseBody
    public String updatePcCookie(@RequestBody JSONObject jsonObject) {
        String detailId = jsonObject.getString("detailId");
        String pcCookie = jsonObject.getString("pcCookie");
        String userId = jsonObject.getString("userId");
        userId = desHelper.decrypt(userId);
        Integer integer = detailsService.updatePcCookie(Long.parseLong(detailId), pcCookie, userId);
        return integer.toString();
    }

    @RequestMapping(value = "/refreshIp", method = RequestMethod.POST)
    @ResponseBody
    public boolean refreshIp(@RequestBody JSONObject jsonObject) {
        String port = jsonObject.getString("port");
        if (!EasyUtil.isEmpty(port)) {
            boolean b = EasyUtil.refreshIp("127.0.0.1",port);
            return b;
        }
        return false;
    }

    @RequestMapping(value = "/getRegisterIp", method = RequestMethod.POST)
    @ResponseBody
    public String getRegisterIp(@RequestBody JSONObject jsonObject) {
        String address = jsonObject.getString("address");
        String port = jsonObject.getString("port");
        try {
            String registerIp = EasyUtil.getRegisterIp(address, port);
            return registerIp;
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("错误信息:" + e.getMessage());
        }
        return "";
    }

    @RequestMapping(value = "/getTaskList", method = RequestMethod.POST)
    @ResponseBody
    public String getTaskList(@RequestBody JSONObject jsonObject) {
        String taskName = jsonObject.getString("taskName");
        String userId = jsonObject.getString("userId");
        Integer type = jsonObject.getInteger("type");
        String country = jsonObject.getString("country");
        country = convertCountry(country);
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(taskName)) {
            String userIdDEC = desHelper.decrypt(userId);
            List<TaskItem> taskItemList = taskItemService.findAllByUserIdAndTypeAndTaskNameAndFinishAndCountry(userIdDEC, type, taskName, false,country);
            return JSONObject.toJSONString(taskItemList);
        }
        return "";
    }

    @RequestMapping(value = "/getTaskAccount", method = RequestMethod.POST)
    @ResponseBody
    public String getTaskAccount(@RequestBody JSONObject jsonObject){
        String taskItemId = jsonObject.getString("taskItemId");
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        country = convertCountry(country);
        String userIdDEC = desHelper.decrypt(userId);
        List<Details> detailsList = detailsService.findByUserIdAndCountryQuery(userIdDEC, country);
        List<Details> collect = detailsList.stream().filter(f -> {
            List<TaskManage> taskManage = taskManageService.findByUserIdAndDetailIdAndTaskItemId(userIdDEC, f.getId(), Long.parseLong(taskItemId));
            if (taskManage.size() == 0) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        if (collect != null&&collect.size()>0) {
            return JSONObject.toJSONString(JSONObject.toJSONString(collect.get(0)));
        }
        return "";
    }
}
